package com.gjq.springboot.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSServerSocketFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.protocol.ftp.FtpURLConnection;

import javax.net.ssl.SSLContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


public class FtpUtil {

    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "192.168.188.129";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "userfile";  //userfile
    //密码
    private static final String FTP_PASSWORD = "gjq548893";  //gjq548893
    //打开路径
    public static final String FTP_BASEPATH = ""; // /home/userfile/file


    //上传1
//    public static int uploadFile(String originFileName, InputStream input,String path) {
//        boolean success = false;
//        FTPClient ftpClient = getConnection();//这是最开始引入的依赖里的方法
//        ftpClient.setControlEncoding("utf-8");
//        if (path!=FTP_BASEPATH){
//            try {
//                //System.out.println("变了"+zPath);
//                //ftpClient.makeDirectory(path);
//                ftpClient.changeWorkingDirectory(path);
//                System.out.println("upload_path "+path);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        try {
//            FTPFile[] ftpFiles = ftpClient.listFiles();
//            for (FTPFile ftpFile:ftpFiles){
//                if(originFileName.equals(ftpFile.getName())) return 1;//出现重名文件
//            }
//            success = ftpClient.storeFile(originFileName, input);
//            input.close();
//            ftpClient.logout();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally {
//            if (ftpClient.isConnected()) {
//                try {
//                    ftpClient.disconnect();
//                } catch (IOException ioe) {
//                    ioe.printStackTrace();
//                }
//            }
//        }
//        if(success == true) return 0;//上传成功
//        return 2; //权限问题
//    }
    //上传2
    public static boolean uploadFile(String originFileName, InputStream input,String path) {
        boolean success = false;
        FTPClient ftpClient = getConnection();//这是最开始引入的依赖里的方法
        ftpClient.setControlEncoding("utf-8");
        if (path!=FTP_BASEPATH){
            try {
                //System.out.println("变了"+zPath);
                //ftpClient.makeDirectory(path);
                ftpClient.changeWorkingDirectory(path);
                System.out.println("upload_path "+path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();
            originFileName = addWei(ftpFiles, originFileName);
            System.out.println("final "+originFileName);
            success = ftpClient.storeFile(originFileName, input);
            input.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return success;
    }
    //重名文件处理
    public static String addWei(FTPFile[] ftpFiles, String originFileName){
        for (FTPFile ftpFile : ftpFiles){
            if(originFileName.equals(ftpFile.getName())){
                        System.out.println("3 "+originFileName);
                        //同名文件 递归
                        String filename = ftpFile.getName();
                        String suffix = filename.substring(filename.lastIndexOf("."));
                        String forth = filename.substring(0,filename.lastIndexOf("."));
                        if(forth.length()<4){
                            originFileName = forth +"(1)"+suffix;
                            return addWei(ftpFiles, originFileName);
                        }else{
                            String wei = forth.substring(forth.length()-3, forth.length());
                            String qian = forth.substring(0, forth.length()-3);
                            //System.out.println(wei);
                            //System.out.println(qian);
                            if(wei.charAt(0) == '(' && wei.charAt(2) == ')'){
                                int time = Integer.valueOf(wei.charAt(1)) - 48;
                                System.out.println("time"+time);
                                time++;
                                wei = "(" + time +")";
                                originFileName = qian + wei +suffix;
                                System.out.println("2 "+originFileName);
                                return addWei(ftpFiles, originFileName);
                            }else{
                                originFileName = forth +"(1)"+suffix;
                                System.out.println("(1)");
                                return addWei(ftpFiles, originFileName);
                            }
                        }
            }
        }
        System.out.println("final_qian "+originFileName);
        return originFileName;
    }

    // 连接ftp
    public static FTPClient getConnection() {
        //CommandUtil.linuxCmd("setenforce 0");
        //FTPSServerSocketFactory ftpsServerSocketFactory = new FTPSServerSocketFactory(SSLContext.getInstance());
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            // 设置连接机器
            ftpClient.connect(FTP_ADDRESS, FTP_PORT);
            ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("ftp连接失败");
                ftpClient.disconnect(); // 断开连接
                return null;
            } else {

                System.out.println("ftp连接成功");
            }
            ftpClient.type(FTPClient.BINARY_FILE_TYPE);
            // 将文件类型设置成二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 创建要存储文件夹的目录: 主要目录只能一级一级创建，不能一次创建多层; 在 选择创建目录是一定要看是否有写权限，不然失败
            //if(path==null) path = FTP_BASEPATH;
            //System.out.println(FTP_BASEPATH);
            ftpClient.makeDirectory(FTP_BASEPATH);
            // 改变默认存放的位置
            ftpClient.changeWorkingDirectory(FTP_BASEPATH);
            System.out.println("连接位置为 "+FTP_BASEPATH);
            //开启被动模式，否则文件上传不成功，也不报错
            ftpClient.enterLocalPassiveMode();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return null;
        }
        return ftpClient;
    }

    //获取文件信息
    public static Object getFile(String path){
        FTPClient ftpClient = getConnection();

        if(ftpClient == null){
            System.out.println("未连接到服务器");
            return false;
        }
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();
            System.out.println(ftpFiles.length);
            return ftpFiles;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    //下载
//    public static boolean downloadFile( String localPath, String fileName, String zPath) {
//        FTPClient ftpClient = getConnection();
//        if(zPath!=FTP_BASEPATH){
//            try {
//                //System.out.println("变了"+zPath);
//                ftpClient.makeDirectory(zPath);
//                ftpClient.changeWorkingDirectory(zPath);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        if (ftpClient == null) {
//            System.out.println("未连接到服务器");
//            return false;
//        }
//        try {
//            FTPFile[] ftpFiles = ftpClient.listFiles();
//            boolean result = false;
//            for (FTPFile ftpFile : ftpFiles) {
//                //System.out.println(ftpFile.getName());
//                if (fileName.equals(ftpFile.getName())) {
//                    if (localPath.charAt(localPath.length()-1) != '/')
//                        localPath = localPath + "/";
//                    File file = new File(fileName);
//                    OutputStream outputStream = new FileOutputStream(file);
//                    //result = ftpClient.retrieveFile(fileName, outputStream);
//                    System.out.println(localPath+fileName);
//                    result = ftpClient.retrieveFile(fileName, outputStream);
//                    //System.out.println("下载结果：" + result);
//                    outputStream.close();
//                }
//            }
//            ftpClient.logout();
//            System.out.println(result);
//            return result;
//        } catch (IOException e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
    public static byte[] downloadFile( String fileName, String zPath) {
        FTPClient ftpClient = getConnection();
        if(zPath!=FTP_BASEPATH){
            try {
                //System.out.println("变了"+zPath);
                ftpClient.makeDirectory(zPath);
                ftpClient.changeWorkingDirectory(zPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (ftpClient == null) {
            System.out.println("未连接到服务器");
            //return false
            return null;
        }
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();
            boolean result = false;
            byte[] fileContent = null;
            for (FTPFile ftpFile : ftpFiles) {
                if (fileName.equals(ftpFile.getName())) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    result = ftpClient.retrieveFile(fileName, outputStream);
                    fileContent = outputStream.toByteArray();
                    outputStream.close();
                }
            }
            ftpClient.logout();
            System.out.println(result);
            return fileContent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


//    @WebServlet(name = "servletContextDemo6", value = "/servletContextDemo6")
//    public class downFileWeb extends HttpServlet {
//        FTPClient ftpClient = getConnection();
//        @Override
//        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//            String filename = request.getParameter("filename");           //获取请求参数
//
//            //使用字节输入流加载文件进内存
//            ServletContext servletContext = this.getServletContext();
//            String realPath = servletContext.getRealPath("/WEB-INF/classes/servletContext/" + filename);  //找到文件的服务器路径
//            FileInputStream fis = new FileInputStream(realPath);                    //使用字节输入流读取文件
//
//            //设置response响应头
//            String mimeType = servletContext.getMimeType(filename);                   //获取mime类型
//            response.setHeader("content-type",mimeType);                              //设置响应头类型
//            response.setHeader("content-disposition","attachment;filename=" + filename);    //设置响应头打开方式
//
//            //将输入流的事件写出到输出事件
//            ServletOutputStream sos = response.getOutputStream();
//            byte[] buffer = new byte[1024 * 8];
//            int length = 0;
//            while((length = fis.read(buffer)) != -1){
//                sos.write(buffer,0,length);
//            }
//            sos.close();
//        }
//
//        @Override
//        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//            this.doGet(request,response);
//        }
//    }
    //新建文件夹
    public static boolean addFolder(String filename, String path){
        FTPClient ftpClient = getConnection();
        //System.out.println("创建文件夹"+filename+" "+path);
        if(ftpClient == null){
            System.out.println("未连接到服务器");
            return false;
        }
        try {
            System.out.println(path+"/"+filename);
            return ftpClient.makeDirectory(path+"/"+filename);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    //打开文件夹
    public static Object openFolder(String path){
        FTPClient ftpClient = getConnection();
        System.out.println(path);
        // 改变默认存放的位置
        try {
            ftpClient.makeDirectory(path);
            ftpClient.changeWorkingDirectory(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();
            return ftpFiles;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


}
